import { Component, OnInit } from '@angular/core';
import { Router,NavigationExtras } from '@angular/router';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { DefaultLanguageService } from '@services/default-language.service';
import { TranslateService } from '@ngx-translate/core';
import { CommonResponse,VerificationType,ToastColor,CommonService,AppVerificationCode } from '@services/common-service.service';
import { AuthTokenService } from '@services/auth-token.service';
import { HttpClient,HttpErrorResponse } from "@angular/common/http";

@Component({
  selector: 'app-mobile-number-edit',
  templateUrl: './mobile-number-edit.page.html',
  styleUrls: ['./mobile-number-edit.page.scss'],
})
export class MobileNumberEditPage implements OnInit {

  constructor(private router:Router,
    private defaultLanguageService:DefaultLanguageService,
    private translate:TranslateService,
    private commonService:CommonService,
    private authTokenService:AuthTokenService,
    private http:HttpClient) { }

  public loading:boolean = false;

  private i18n:any = {};

  public validateForm:FormGroup;
  ngOnInit() {
    this.initLanguage();
    this.validateForm = new FormGroup({
      'mobileNumber': new FormControl('', [
        Validators.required,
        Validators.pattern('\\d{6,}')
      ])
    })
  }

  initLanguage(){
    this.i18n = this.commonService.initTranslate([]); 
  }

  get mobileNumber(){return this.validateForm.get('mobileNumber');}

  verifyMobile(){
    if(this.validateForm.invalid){
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return false;
    }
    this.loading = true;
    var api = "/scm/app/checkMobileNumber.do";
    let requestJson = {
      'appUserId':this.authTokenService.getAppUserId(),
      'mobileNumber':this.validateForm.value.mobileNumber
    }
    this.http.post(api,requestJson).subscribe((response:CommonResponse)=>{
      if(response.isSuccess){
        let navigationExtras: NavigationExtras = {
          queryParams: { 'mobileNumber': this.validateForm.value.mobileNumber }
        };
        this.router.navigate(['/tabs/myAccount/setting/account-security/mobile-number/mobile-number-edit/mobile-number-verify'],navigationExtras);
      }
      this.loading = false;
    },(errorResponse:HttpErrorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
      this.loading = false;
    })
  }

}
